package cn.ncu.wechat.util;

import cn.ncu.wechat.model.ApiResponse;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class ThirdPartyApiClient {

    public static String callThirdPartyApi() {
        try {
            String userId = "HM%40HNQH_2025";
            // 对 userId 进行一次 URL 编码
            String encodedUserId = URLEncoder.encode(userId, StandardCharsets.UTF_8.toString());

            // 构建 URL，将编码后的 userId 作为参数动态传入
            String url = "http://hnqhyl.gnway.vip:17435/ZsbAuthorization/accessToken?userId=HM%40HNQH_2025";
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();

            // 设置请求方法为 POST
            con.setRequestMethod("POST");
            // 添加请求头
            con.setRequestProperty("accept", "*/*");

            // 获取响应
            int responseCode = con.getResponseCode();
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // 打印原始响应
            System.out.println("Raw Response: " + response.toString());

            // 解析 JSON 响应
            ObjectMapper objectMapper = new ObjectMapper();
            ApiResponse apiResponse = objectMapper.readValue(response.toString(), ApiResponse.class);

            String jwtToken = "Error";
            // 检查响应状态
            if (apiResponse.getCode() == 0) {
                // 提取 data 字段中的 JWT
                jwtToken = apiResponse.getData();
                System.out.println("JWT Token: " + jwtToken);
            } else {
                // 打印错误信息
                System.out.println("Error: " + apiResponse.getMsg());
            }
            return jwtToken;
        } catch (Exception e) {
            e.printStackTrace();
            return "Exception: " + e.getMessage();
        }
    }

        public static String sendPostRequest(String url) {
            StringBuilder response = new StringBuilder();
            try {
                URL obj = new URL(url);
                HttpURLConnection con = (HttpURLConnection) obj.openConnection();
                con.setRequestMethod("POST");
                con.setRequestProperty("accept", "*/*");

                int responseCode = con.getResponseCode();
                System.out.println("Response Code : " + responseCode);

                BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String inputLine;

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return response.toString();
        }


    public static String sendGetRequest(String token,Map<String, String> queryParams) {
        String url = "http://hnqhyl.gnway.vip:17435/zsbCtmZpt/select";
        String urlWithQueryParams= buildUrlWithQueryParams(url,queryParams);
        StringBuilder response = new StringBuilder();
        String jsonResponse = "error";
        try {
            URL obj = new URL(urlWithQueryParams);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("GET");
            con.setRequestProperty("Authorization", "Bearer "+token); // 设置 Authorization 头

            int responseCode = con.getResponseCode();
            System.out.println("Response Code: " + responseCode);

            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            jsonResponse = response.toString();
            if (jsonResponse.contains("\"data\":[")) {
                jsonResponse = jsonResponse.replace("[", "{");
                jsonResponse = jsonResponse.replace("]", "}");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonResponse;
    }


    public static String getCardType(String mtyCode,String mtyName,String sort,String page,String size,String token) {
        String baseUrl = "http://hnqhyl.gnway.vip:17435/memberType/select";
        Map<String, String> queryParams = new HashMap<>();
        addParamIfNotEmpty(queryParams, "mtyCode", mtyCode);
        addParamIfNotEmpty(queryParams, "mtyName", mtyName);
        addParamIfNotEmpty(queryParams, "sort", sort);
        addParamIfNotEmpty(queryParams, "page", page);
        addParamIfNotEmpty(queryParams, "size", size);
        String urlWithParams = buildUrlWithQueryParams(baseUrl, queryParams);
        return getMemberCardType(urlWithParams, token);
    }



    /**
     * 如果参数不为空，则将其添加到 Map 中
     *
     * @param params  Map 对象
     * @param key     参数名
     * @param value   参数值
     */
    public static void addParamIfNotEmpty(Map<String, String> params, String key, String value) {
        if (value != null && !value.trim().isEmpty()) {
            params.put(key, value);
        }
    }

    /**
     * 构建带查询参数的 URL
     *
     * @param baseUrl     基础 URL
     * @param queryParams 查询参数
     * @return 完整的 URL
     */
    public static String buildUrlWithQueryParams(String baseUrl, Map<String, String> queryParams) {
        StringBuilder urlBuilder = new StringBuilder(baseUrl);
        if (!queryParams.isEmpty()) {
            urlBuilder.append("?");
            for (Map.Entry<String, String> entry : queryParams.entrySet()) {
                urlBuilder.append(entry.getKey())
                        .append("=")
                        .append(entry.getValue())
                        .append("&");
            }
            // 删除最后一个多余的 "&"
            urlBuilder.deleteCharAt(urlBuilder.length() - 1);
        }
        return urlBuilder.toString();
    }

    /**
     * 发送 GET 请求查询会员卡类型
     *
     * @param url   完整的 URL（包含查询参数）
     * @param token Authorization Token
     * @return 服务器响应内容
     */
    public static String getMemberCardType(String url, String token) {
        StringBuilder response = new StringBuilder();
        String jsonResponse = "error";
        try {
            System.out.println(token);
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("GET");
            con.setRequestProperty("Authorization", "Bearer "+token); // 设置 Authorization 头
            int responseCode = con.getResponseCode();
            System.out.println("Response Code: " + responseCode);
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            jsonResponse = response.toString();
            if (jsonResponse.contains("\"data\":[")) {
                jsonResponse = jsonResponse.replace("[", "{");
                jsonResponse = jsonResponse.replace("]", "}");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(response);
        return jsonResponse;
    }

}
